package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDTO;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * author by itheima
 *
 * @Date 2022/3/15
 * Description
 */
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BehaviorFeign behaviorFeign;
    /**
     * 保存用户搜索历史记录
     * @param dto
     */
    @Override
    @Async("taskExecutor")
    public void insert(UserSearchDTO dto) {
        // 查询行为实体
        ResponseResult<ApBehaviorEntry> behaviorResult = behaviorFeign.findByUserIdOrEquipmentId(dto.getEntryId(),dto.getEquipmentId());
        if (!behaviorResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用实体失败");
        }
        ApBehaviorEntry behaviorEntry = behaviorResult.getData();
        if(behaviorEntry==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"为查询到行为实体");
        }
        // 判断历史记录是否存在
        ApUserSearch userSearch = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()).and("keyword").is(dto.getSearchWords())), ApUserSearch.class);
        // 如果存在历史记录  更新 创建时间
        if(userSearch!=null){
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch);
            return;
        }
        // 如果不存在  新增历史记录
         userSearch = new ApUserSearch();
        userSearch.setEntryId(behaviorEntry.getId());
        userSearch.setKeyword(dto.getSearchWords());
        userSearch.setCreatedTime(new Date());
        mongoTemplate.save(userSearch);
    }

    @Override
    public ResponseResult findUserSearch(UserSearchDTO dto) {
        // 1. 根据用户id 或 设备id 获取行为实体对象
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if(!behaviorResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用行为实体失败");
       }
        ApBehaviorEntry behaviorEntry = behaviorResult.getData();
        if(behaviorEntry==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到行为实体");
        }
        // 2. 根据行为实体id  按照创建时间降序排序  查询最近10条搜索历史记录
        int size = 10;
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("entryId").is(behaviorEntry.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(size), ApUserSearch.class
        );
        // 3. 得到的集合返回
        return ResponseResult.okResult(apUserSearches);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDTO dto) {
      //判断参数
        if(dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //登录用户远程调用
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorEntryResult = behaviorFeign.findByUserIdOrEquipmentId(user == null ? null : user.getId(), dto.getEquipmentId());
        if(!behaviorEntryResult.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用行为服务失败");
        }
        ApBehaviorEntry behaviorEntry = behaviorEntryResult.getData();
        if(behaviorEntry==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
    mongoTemplate.remove(Query.query(Criteria.where("_id").is(dto.getId()).and("entryId").is(behaviorEntry.getId())),ApUserSearch.class);
        }
        return ResponseResult.okResult();
    }
}
